﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ShoppingPartListControl : RSBaseUserControl
    {
        private int _workorderid = 0;
        private int _Estimateid = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["workorderid"] != null)
                    _workorderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
                if (Request.QueryString["Estimateid"] != null)
                    _Estimateid = Convert.ToInt32(Request.QueryString["Estimateid"].ToString());

                hfWorkOrderId.Value = _workorderid.ToString();
                hfEstimateId.Value = _Estimateid.ToString();
            }

        }
        protected void gvShoppingPartList_RowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int selectedid = Convert.ToInt32(gvShoppingPartList.DataKeys[e.RowIndex].Value);
                RemoveSelectedItemFromList(selectedid);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        private void RemoveSelectedItemFromList(int selectedid)
        {
            List<ShoppingPart> selParts = new List<ShoppingPart>();
            if (Session["SHOPPING_PARTLIST"] != null)
                selParts = (List<ShoppingPart>)Session["SHOPPING_PARTLIST"];

            if (selParts.Count > 0)
            {
                for (int i = 0; i < selParts.Count; i++)
                {
                    if (selParts[i].ProductId == selectedid)
                    {
                        selParts.RemoveAt(i);
                        break;
                    }
                }
            }

            Session["SHOPPING_PARTLIST"] = selParts;
            gvShoppingPartList.DataSource = selParts;
            gvShoppingPartList.DataBind();

            if (gvShoppingPartList.Rows.Count > 0)
                pnlShoppingPartList.Visible = true;
            else
                pnlShoppingPartList.Visible = false;
        }

        public void ShowShoppingPartList(int companyid)
        {
            LoadShoppingPartList(companyid);
        }

        protected void btnSubmit_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();

            int companyid = userIdentity.RSCompanyId;
            _Estimateid = hfEstimateId.Value == "" ? 0 : Convert.ToInt32(hfEstimateId.Value);
            _workorderid = hfWorkOrderId.Value == "" ? 0 : Convert.ToInt32(hfWorkOrderId.Value);

            if (_workorderid == 0 && _Estimateid == 0)
            {
                int locationid = 0;
                if (Request.QueryString["locationid"] != null)
                    locationid = Convert.ToInt32(Request.QueryString["locationid"].ToString());
                Response.Redirect("RSAdHocInvoice.aspx?locationid=" + locationid);
            }

            List<ShoppingPart> selParts = new List<ShoppingPart>();
            if (Session["SHOPPING_PARTLIST"] != null)
                selParts = (List<ShoppingPart>)Session["SHOPPING_PARTLIST"];

            string itemname;
            decimal unitprice;
            decimal amount;
            int productid = 0;
            int quantity = 0;
            if (selParts.Count > 0)
            {
                for (int i = 0; i < selParts.Count; i++)
                {
                    itemname = selParts[i].ProductName;
                    unitprice = selParts[i].UnitPrice;
                    productid = Convert.ToInt32(selParts[i].ProductId);
                    quantity = Convert.ToInt32(selParts[i].Quantity);
                    amount = quantity * unitprice;
  
                    if (companyid > 0 && _Estimateid > 0 && productid > 0 && quantity > 0)
                    {
                        SaveSelectedPartToEstimate(companyid, _Estimateid, productid, quantity);
                    }
                    if (companyid > 0 && _workorderid > 0 && productid > 0 && quantity > 0)
                    {
                        SaveSelectedPartToWorkOrder(companyid, _workorderid, productid, quantity);
                    }
                }

                string returnUrl = string.Empty;
                if (Request.QueryString["isEstimate"] == "1")
                    returnUrl = "~/RS/SBM/RSEstimateParts.aspx?estimateid=" + _Estimateid;
                else
                    returnUrl = "~/RS/SBM/RSWorkOrderParts.aspx?workorderid=" + _workorderid;
                ucModalActionMessageControl.ShowModal("Parts Added Successfully!", returnUrl, true);
            }
            Session["SHOPPING_PARTLIST"] = null;

        }
        protected void btnReturn_Click(Object sender, EventArgs e)
        {
            int WorkOrderid = 0;
            if (Request.QueryString["workorderid"] != null)
                WorkOrderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
            int Estimateid = 0;
            if (Request.QueryString["Estimateid"] != null)
                Estimateid = Convert.ToInt32(Request.QueryString["Estimateid"].ToString());

            if (Request.QueryString["isEstimate"] == "1")
                Response.Redirect("~/RS/SBM/RSEstimateParts.aspx?estimateid=" + Estimateid);
            else
                Response.Redirect("~/RS/SBM/RSWorkOrderParts.aspx?workorderid=" + WorkOrderid);
        }
        private void SaveSelectedPartToEstimate(int companyid, int Estimateid, int productid, int quantity)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@quantity", SqlDbType.Int, 0, ParameterDirection.Input, quantity);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@Estimateid", SqlDbType.Int, 0, ParameterDirection.Input, Estimateid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "INSERT INTO rs_tblEstimatePart (Estimateid, productid, quantity, companyid, unitprice) VALUES(@Estimateid, @productid, @quantity, @companyid, (select i.unitprice from rs_tblInventory i where i.productid=@productid and i.companyid=@companyid))");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
        }

        private void SaveSelectedPartToWorkOrder(int companyid, int WorkOrderid, int productid, int quantity)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@quantity", SqlDbType.Int, 0, ParameterDirection.Input, quantity);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "INSERT INTO rs_tblWorkOrderPart (WorkOrderid, productid, quantity, companyid, unitprice) VALUES(@WorkOrderid, @productid, @quantity, @companyid, (select i.unitprice from rs_tblInventory i where i.productid=@productid and i.companyid=@companyid))");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);

        }

        public void LoadShoppingPartList(int companyid)
        {
            if (Session["SHOPPING_PARTLIST"] != null)
            {
                List<ShoppingPart> selParts = new List<ShoppingPart>();
                selParts = (List<ShoppingPart>)Session["SHOPPING_PARTLIST"];

                if (selParts.Count > 0)
                {
                    String strSQL = "SELECT c.ProductId,c.ProductName,c.QuantityPerUnit,c.UnitPrice,c.UnitsInStock,c.UnitsOnOrder, '0' AS Quanity, c.ProductDesc," +
                                        "c.Discontinued,c.ModelNo,c.ProductCode,c.ParentId, (SELECT p.ProductName FROM rs_tblInventory p WHERE p.ProductId=c.ParentId) as CategoryName,c.SupplierID,c.CompanyId " +
                                        " FROM rs_tblInventory c WHERE c.IsEquipment=0 AND c.companyid=@companyid AND c.ParentId > 0  order by CategoryName ";
                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;
                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);
                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        while (myDataReader.Read())
                        {
                            if (selParts.Count > 0)
                            {
                                for (int i = 0; i < selParts.Count; i++)
                                {
                                    if (selParts[i].ProductId == int.Parse(myDataReader["ProductId"].ToString()))
                                    {
                                        selParts[i].ProductName = myDataReader["ProductName"].ToString();
                                        selParts[i].UnitPrice = Convert.ToDecimal(myDataReader["UnitPrice"].ToString());
                                        selParts[i].ParentId = int.Parse(myDataReader["ParentId"].ToString());
                                        selParts[i].ModelNo = myDataReader["ModelNo"].ToString();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    gvShoppingPartList.DataSource = selParts;
                    gvShoppingPartList.DataBind();
                    myConnection.Close();
                    //lblShoppingPartList.Text = "Shopping Part List";
                    pnlShoppingPartList.Visible = true;
                }
                else
                {
                    //lblShoppingPartList.Text = "There are no item in Shopping Part.";
                    //btnSubmit.Enabled = false;
                    pnlShoppingPartList.Visible = false;
                }
            }
        }
    }
}